#!/usr/bin/env node

/**
 * Vue + TypeScript 项目模板生成器
 * 为新项目快速生成完整的配置结构和基础代码
 * 
 * 使用方法：
 * 1. node create-vue-ts-project.js <project-name>
 * 2. cd <project-name>
 * 3. npm install
 * 4. npm run dev
 */

const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
}

function colorLog(color, message) {
  console.log(`${colors[color]}${message}${colors.reset}`)
}

// 项目模板配置
const PROJECT_TEMPLATES = {
  // package.json
  'package.json': (projectName) => ({
    "name": projectName,
    "version": "0.1.0",
    "private": true,
    "type": "module",
    "scripts": {
      "dev": "vite",
      "build": "vue-tsc -b && vite build",
      "preview": "vite preview",
      "check": "vue-tsc -b",
      "lint": "eslint . --ext .ts,.vue",
      "lint:fix": "eslint . --ext .ts,.vue --fix"
    },
    "dependencies": {
      "vue": "^3.4.0",
      "vue-router": "^4.2.0"
    },
    "devDependencies": {
      "@types/node": "^20.10.0",
      "@typescript-eslint/eslint-plugin": "^6.15.0",
      "@typescript-eslint/parser": "^6.15.0",
      "@vitejs/plugin-vue": "^4.5.0",
      "@vue/tsconfig": "^0.5.0",
      "eslint": "^8.56.0",
      "eslint-plugin-vue": "^9.19.0",
      "typescript": "^5.3.0",
      "unplugin-auto-import": "^0.17.0",
      "unplugin-vue-components": "^0.26.0",
      "vite": "^5.0.0",
      "vue-tsc": "^1.8.0"
    }
  }),

  // tsconfig.json
  'tsconfig.json': {
    "files": [],
    "references": [
      { "path": "./tsconfig.node.json" },
      { "path": "./tsconfig.app.json" }
    ]
  },

  // tsconfig.app.json
  'tsconfig.app.json': {
    "extends": "@vue/tsconfig/tsconfig.dom.json",
    "include": [
      "env.d.ts",
      "src/**/*",
      "src/**/*.vue"
    ],
    "exclude": [
      "src/**/__tests__/*"
    ],
    "compilerOptions": {
      "composite": true,
      "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
      "baseUrl": ".",
      "paths": {
        "@/*": ["src/*"]
      }
    }
  },

  // tsconfig.node.json
  'tsconfig.node.json': {
    "extends": "@vue/tsconfig/tsconfig.node.json",
    "include": [
      "vite.config.*",
      "vitest.config.*",
      "cypress.config.*",
      "nightwatch.conf.*",
      "playwright.config.*"
    ],
    "compilerOptions": {
      "composite": true,
      "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
    }
  },

  // vite.config.ts
  'vite.config.ts': `import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 自动导入 Vue API
    AutoImport({
      imports: ['vue', 'vue-router'],
      dts: 'src/types/auto-imports.d.ts',
      eslintrc: {
        enabled: true,
        filepath: './.eslintrc-auto-import.json'
      }
    }),
    // 自动导入组件
    Components({
      dts: 'src/types/components.d.ts'
    })
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  server: {
    port: 3000,
    open: true
  }
})
`,

  // .eslintrc.cjs
  '.eslintrc.cjs': `/*
 * ESLint 配置：与 TypeScript 规则对齐，支持 Vue 3 + <script setup> + TS
 * - 关闭 ESLint 层的未使用变量检测，交由 TypeScript 编译器（TS6133）统一处理
 * - 引入 unplugin-auto-import 生成的全局声明，避免无谓的未定义报错
 */

// 引入自动导入生成的全局变量定义
const autoImportGlobals = (() => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const cfg = require('./.eslintrc-auto-import.json')
    return cfg.globals || {}
  } catch (e) {
    return {}
  }
})()

module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  // 使用 Vue 的解析器，转交 <script> 内容给 TS 解析器
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 'latest',
    sourceType: 'module',
    extraFileExtensions: ['.vue'],
  },
  plugins: ['vue', '@typescript-eslint'],
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  rules: {
    // 与 TS 编译器保持一致：未使用变量交由 TS 处理，避免重复报错
    'no-unused-vars': 'off',
    '@typescript-eslint/no-unused-vars': 'off',

    // 常见工程化约定
    'vue/multi-word-component-names': 'off',
  },
  globals: {
    ...autoImportGlobals,
  },
  ignorePatterns: [
    'dist/',
    'node_modules/',
    'src/types/*.d.ts',
  ],
}
`,

  // env.d.ts
  'env.d.ts': `/// <reference types="vite/client" />
`,

  // src/vite-env.d.ts
  'src/vite-env.d.ts': `/// <reference types="vite/client" />

// 为 .vue 单文件组件提供模块声明，供 TypeScript 识别
// 说明：使用 DefineComponent 的默认泛型，避免使用 \`{}\` 与 \`any\` 以通过更严格的 ESLint 规则
declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent
  export default component
}
`,

  // src/main.ts
  'src/main.ts': `import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './views/Home.vue'
import About from './views/About.vue'

// 路由配置
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 创建应用
const app = createApp(App)
app.use(router)
app.mount('#app')
`,

  // src/App.vue
  'src/App.vue': `<template>
  <div id="app">
    <nav class="navbar">
      <div class="nav-container">
        <h1 class="nav-title">{{ projectTitle }}</h1>
        <div class="nav-links">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/about" class="nav-link">关于</router-link>
        </div>
      </div>
    </nav>
    
    <main class="main-content">
      <router-view />
    </main>
  </div>
</template>

<script setup lang="ts">
// 项目标题
const projectTitle = 'Vue + TypeScript 项目'
</script>

<style scoped>
#app {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.navbar {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 1rem 0;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-title {
  color: white;
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
}

.nav-links {
  display: flex;
  gap: 2rem;
}

.nav-link {
  color: white;
  text-decoration: none;
  font-weight: 500;
  transition: opacity 0.3s ease;
}

.nav-link:hover,
.nav-link.router-link-active {
  opacity: 0.8;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}
</style>
`,

  // src/views/Home.vue
  'src/views/Home.vue': `<template>
  <div class="home">
    <div class="hero">
      <h1 class="hero-title">欢迎使用 Vue + TypeScript</h1>
      <p class="hero-subtitle">现代化的前端开发体验</p>
      
      <div class="features">
        <div class="feature-card">
          <h3>⚡ 快速开发</h3>
          <p>Vite 提供极速的开发体验</p>
        </div>
        
        <div class="feature-card">
          <h3>🔧 类型安全</h3>
          <p>TypeScript 确保代码质量</p>
        </div>
        
        <div class="feature-card">
          <h3>📦 自动导入</h3>
          <p>无需手动导入 Vue API</p>
        </div>
      </div>
      
      <div class="counter-demo">
        <h3>计数器演示</h3>
        <div class="counter">
          <button @click="decrement" class="counter-btn">-</button>
          <span class="counter-value">{{ count }}</span>
          <button @click="increment" class="counter-btn">+</button>
        </div>
        <p class="counter-text">当前计数: {{ count }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 使用自动导入的 ref，无需手动导入
const count = ref(0)

// 计数器方法
const increment = () => {
  count.value++
}

const decrement = () => {
  count.value--
}
</script>

<style scoped>
.home {
  color: white;
}

.hero {
  text-align: center;
  padding: 2rem 0;
}

.hero-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 1rem;
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.hero-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: 3rem;
}

.features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.feature-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 2rem;
  transition: transform 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
}

.feature-card h3 {
  font-size: 1.3rem;
  margin-bottom: 1rem;
}

.feature-card p {
  opacity: 0.9;
  line-height: 1.6;
}

.counter-demo {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 2rem;
  max-width: 400px;
  margin: 0 auto;
}

.counter {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin: 1rem 0;
}

.counter-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 1.2rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.counter-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.counter-value {
  font-size: 2rem;
  font-weight: bold;
  min-width: 60px;
}

.counter-text {
  margin-top: 1rem;
  opacity: 0.9;
}
</style>
`,

  // src/views/About.vue
  'src/views/About.vue': `<template>
  <div class="about">
    <div class="about-content">
      <h1 class="about-title">关于项目</h1>
      
      <div class="about-grid">
        <div class="about-card">
          <h3>🚀 技术栈</h3>
          <ul class="tech-list">
            <li>Vue 3 - 渐进式 JavaScript 框架</li>
            <li>TypeScript - 类型安全的 JavaScript</li>
            <li>Vite - 下一代前端构建工具</li>
            <li>Vue Router - 官方路由管理器</li>
            <li>ESLint - 代码质量检查工具</li>
          </ul>
        </div>
        
        <div class="about-card">
          <h3>✨ 特性</h3>
          <ul class="feature-list">
            <li>⚡ 极速的开发体验</li>
            <li>🔧 完整的 TypeScript 支持</li>
            <li>📦 自动导入 Vue API</li>
            <li>🎨 现代化的 UI 设计</li>
            <li>🔍 ESLint 代码检查</li>
            <li>🚀 优化的生产构建</li>
          </ul>
        </div>
      </div>
      
      <div class="project-info">
        <h3>📊 项目信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">创建时间:</span>
            <span class="info-value">{{ createTime }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">Vue 版本:</span>
            <span class="info-value">{{ vueVersion }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">构建工具:</span>
            <span class="info-value">Vite</span>
          </div>
          <div class="info-item">
            <span class="info-label">开发语言:</span>
            <span class="info-value">TypeScript</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 使用自动导入的 computed，无需手动导入
const createTime = computed(() => {
  return new Date().toLocaleDateString('zh-CN')
})

const vueVersion = computed(() => {
  return '3.4+'
})
</script>

<style scoped>
.about {
  color: white;
}

.about-content {
  max-width: 800px;
  margin: 0 auto;
}

.about-title {
  font-size: 2.5rem;
  font-weight: 700;
  text-align: center;
  margin-bottom: 2rem;
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.about-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.about-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 2rem;
}

.about-card h3 {
  font-size: 1.3rem;
  margin-bottom: 1rem;
}

.tech-list,
.feature-list {
  list-style: none;
  padding: 0;
}

.tech-list li,
.feature-list li {
  padding: 0.5rem 0;
  opacity: 0.9;
  line-height: 1.6;
}

.project-info {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 2rem;
}

.project-info h3 {
  font-size: 1.3rem;
  margin-bottom: 1rem;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.info-label {
  font-weight: 500;
  opacity: 0.8;
}

.info-value {
  font-weight: 600;
}
</style>
`,

  // .gitignore
  '.gitignore': `# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

# Environment variables
.env
.env.local
.env.*.local

# TypeScript
*.tsbuildinfo

# ESLint
.eslintcache

# Auto-generated files
src/types/auto-imports.d.ts
src/types/components.d.ts
.eslintrc-auto-import.json
`,

  // README.md
  'README.md': (projectName) => `# ${projectName}

一个使用 Vue 3 + TypeScript + Vite 构建的现代化前端项目。

## ✨ 特性

- ⚡ **Vite** - 极速的开发体验
- 🔧 **TypeScript** - 完整的类型安全支持
- 📦 **自动导入** - Vue API 和组件自动导入
- 🎨 **现代化 UI** - 精美的界面设计
- 🔍 **ESLint** - 代码质量检查
- 🚀 **优化构建** - 生产环境优化

## 🛠️ 技术栈

- [Vue 3](https://vuejs.org/) - 渐进式 JavaScript 框架
- [TypeScript](https://www.typescriptlang.org/) - 类型安全的 JavaScript
- [Vite](https://vitejs.dev/) - 下一代前端构建工具
- [Vue Router](https://router.vuejs.org/) - 官方路由管理器
- [ESLint](https://eslint.org/) - 代码质量检查工具

## 🚀 快速开始

### 安装依赖

\`\`\`bash
npm install
# 或
pnpm install
# 或
yarn install
\`\`\`

### 开发

\`\`\`bash
npm run dev
\`\`\`

### 构建

\`\`\`bash
npm run build
\`\`\`

### 预览

\`\`\`bash
npm run preview
\`\`\`

### 代码检查

\`\`\`bash
# TypeScript 类型检查
npm run check

# ESLint 代码检查
npm run lint

# ESLint 自动修复
npm run lint:fix
\`\`\`

## 📁 项目结构

\`\`\`
${projectName}/
├── public/                 # 静态资源
├── src/
│   ├── views/             # 页面组件
│   ├── types/             # 类型声明文件
│   ├── App.vue            # 根组件
│   ├── main.ts            # 入口文件
│   └── vite-env.d.ts      # Vite 环境声明
├── .eslintrc.cjs          # ESLint 配置
├── tsconfig.json          # TypeScript 配置
├── tsconfig.app.json      # 应用 TypeScript 配置
├── tsconfig.node.json     # Node.js TypeScript 配置
├── vite.config.ts         # Vite 配置
└── package.json           # 项目配置
\`\`\`

## 🔧 配置说明

### TypeScript 配置

项目使用了分层的 TypeScript 配置：
- \`tsconfig.json\` - 根配置
- \`tsconfig.app.json\` - 应用代码配置
- \`tsconfig.node.json\` - Node.js 工具配置

### ESLint 配置

- 支持 Vue 3 和 TypeScript
- 自动导入的 API 无需手动声明
- 与 TypeScript 编译器规则对齐

### 自动导入

项目配置了自动导入功能：
- Vue API (ref, reactive, computed 等)
- Vue Router API
- 组件自动注册

## 📝 开发指南

### 添加新页面

1. 在 \`src/views/\` 目录下创建新的 Vue 组件
2. 在 \`src/main.ts\` 中添加路由配置
3. 在导航栏中添加链接

### 使用 TypeScript

项目完全支持 TypeScript，建议：
- 为组件 props 定义接口
- 使用类型注解提升代码质量
- 利用 IDE 的类型提示功能

### 代码规范

- 使用 ESLint 检查代码质量
- 遵循 Vue 3 最佳实践
- 保持代码简洁和可读性

## 🤝 贡献

欢迎提交 Issue 和 Pull Request！

## 📄 许可证

MIT License
`,

  // index.html
  'index.html': (projectName) => `<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${projectName}</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      
      body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
          'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
          sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
`,

  // public/vite.svg
  'public/vite.svg': `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>`
}

/**
 * 创建项目目录结构
 */
function createProjectStructure(projectName) {
  colorLog('blue', `📁 创建项目目录: ${projectName}`)
  
  if (fs.existsSync(projectName)) {
    colorLog('red', `❌ 目录 ${projectName} 已存在`)
    process.exit(1)
  }
  
  // 创建主目录
  fs.mkdirSync(projectName)
  
  // 创建子目录
  const directories = [
    'src',
    'src/views',
    'src/types',
    'public'
  ]
  
  directories.forEach(dir => {
    fs.mkdirSync(path.join(projectName, dir), { recursive: true })
  })
  
  colorLog('green', '✅ 项目目录创建完成')
}

/**
 * 生成项目文件
 */
function generateProjectFiles(projectName) {
  colorLog('blue', '📝 生成项目文件...')
  
  Object.entries(PROJECT_TEMPLATES).forEach(([filename, content]) => {
    const filePath = path.join(projectName, filename)
    const dir = path.dirname(filePath)
    
    // 确保目录存在
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true })
    }
    
    // 生成文件内容
    let fileContent
    if (typeof content === 'function') {
      fileContent = content(projectName)
    } else {
      fileContent = content
    }
    
    // 写入文件
    if (typeof fileContent === 'object') {
      fs.writeFileSync(filePath, JSON.stringify(fileContent, null, 2) + '\n')
    } else {
      fs.writeFileSync(filePath, fileContent)
    }
    
    colorLog('green', `✅ 创建: ${filename}`)
  })
}

/**
 * 安装依赖
 */
function installDependencies(projectName) {
  colorLog('blue', '📦 安装依赖...')
  
  try {
    process.chdir(projectName)
    
    // 检测可用的包管理器
    let packageManager = 'npm'
    try {
      execSync('pnpm --version', { stdio: 'pipe' })
      packageManager = 'pnpm'
    } catch {
      try {
        execSync('yarn --version', { stdio: 'pipe' })
        packageManager = 'yarn'
      } catch {
        // 使用默认的 npm
      }
    }
    
    colorLog('cyan', `使用 ${packageManager} 安装依赖...`)
    
    const installCmd = packageManager === 'yarn' ? 'yarn install' : `${packageManager} install`
    execSync(installCmd, { stdio: 'inherit' })
    
    colorLog('green', '✅ 依赖安装完成')
    return packageManager
  } catch (error) {
    colorLog('red', '❌ 依赖安装失败')
    colorLog('yellow', '请手动运行: npm install')
    return 'npm'
  }
}

/**
 * 初始化 Git 仓库
 */
function initGitRepository() {
  colorLog('blue', '🔧 初始化 Git 仓库...')
  
  try {
    execSync('git init', { stdio: 'pipe' })
    execSync('git add .', { stdio: 'pipe' })
    execSync('git commit -m "Initial commit"', { stdio: 'pipe' })
    colorLog('green', '✅ Git 仓库初始化完成')
  } catch (error) {
    colorLog('yellow', '⚠️ Git 初始化失败，请手动初始化')
  }
}

/**
 * 显示完成信息
 */
function showCompletionInfo(projectName, packageManager) {
  console.log('')
  colorLog('green', '🎉 项目创建完成！')
  
  console.log('')
  colorLog('blue', '🚀 开始开发：')
  console.log(`   cd ${projectName}`)
  console.log(`   ${packageManager} run dev`)
  
  console.log('')
  colorLog('blue', '🔧 可用命令：')
  console.log(`   ${packageManager} run dev       # 启动开发服务器`)
  console.log(`   ${packageManager} run build     # 构建生产版本`)
  console.log(`   ${packageManager} run preview   # 预览生产构建`)
  console.log(`   ${packageManager} run check     # TypeScript 类型检查`)
  console.log(`   ${packageManager} run lint      # ESLint 代码检查`)
  console.log(`   ${packageManager} run lint:fix  # ESLint 自动修复`)
  
  console.log('')
  colorLog('blue', '📚 项目特性：')
  console.log('   ⚡ Vite - 极速开发体验')
  console.log('   🔧 TypeScript - 完整类型支持')
  console.log('   📦 自动导入 - Vue API 和组件')
  console.log('   🎨 现代化 UI - 精美界面设计')
  console.log('   🔍 ESLint - 代码质量检查')
  
  console.log('')
  colorLog('cyan', '💡 提示：重启 IDE 以获得最佳开发体验')
}

/**
 * 主函数
 */
function main() {
  const args = process.argv.slice(2)
  
  if (args.length === 0) {
    console.log('')
    colorLog('red', '❌ 请提供项目名称')
    console.log('')
    colorLog('blue', '使用方法：')
    console.log('   node create-vue-ts-project.js <project-name>')
    console.log('')
    colorLog('blue', '示例：')
    console.log('   node create-vue-ts-project.js my-vue-app')
    process.exit(1)
  }
  
  const projectName = args[0]
  
  // 验证项目名称
  if (!/^[a-zA-Z0-9-_]+$/.test(projectName)) {
    colorLog('red', '❌ 项目名称只能包含字母、数字、连字符和下划线')
    process.exit(1)
  }
  
  console.log('')
  colorLog('magenta', '🚀 Vue + TypeScript 项目生成器')
  colorLog('cyan', `   正在创建项目: ${projectName}`)
  console.log('')
  
  try {
    // 1. 创建项目结构
    createProjectStructure(projectName)
    
    // 2. 生成项目文件
    generateProjectFiles(projectName)
    
    // 3. 安装依赖
    const packageManager = installDependencies(projectName)
    
    // 4. 初始化 Git
    initGitRepository()
    
    // 5. 显示完成信息
    showCompletionInfo(projectName, packageManager)
    
  } catch (error) {
    console.log('')
    colorLog('red', '❌ 项目创建失败:')
    console.error(error.message)
    process.exit(1)
  }
}

// 如果直接运行此脚本，执行主函数
if (require.main === module) {
  main()
}

// 导出函数供其他模块使用
module.exports = {
  createProjectStructure,
  generateProjectFiles,
  installDependencies,
  PROJECT_TEMPLATES
}